package com.eranga.project.control.data;

import java.util.ArrayList;

import com.eranga.project.model.Area;
import com.eranga.project.model.AreaCoordinates;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class AreaDS {
	private SQLiteDatabase dB;
	private DatabaseHelper dbHelper;
	Context context;
	
	public AreaDS (Context context){
		this.context = context;
		dbHelper = new DatabaseHelper(context);
	}
	
	public void open() throws SQLException {
		dB = dbHelper.getWritableDatabase();
	}
	
	
	
	public int createArea(Area area) {
		if(dB == null){
			open();
		}else if(!dB.isOpen()){
			open();
		}
		
		ContentValues values = new ContentValues();
		values.put(dbHelper.AREA_NAME, area.getAreaName());
		values.put(dbHelper.AREA_SPEED_LIMIT, area.getSpeedLimit());
				
		int id = (int) dB.insert(dbHelper.TABLE_AREA_DETAILS, null, values);
		dB.close();
		return id;
		
	}
	
	
	public ArrayList<Area> getAllArea() {
		if (dB == null) {
			open();
		} else if (!dB.isOpen()) {
			open();
		}
		
		ArrayList<Area> results = new ArrayList<Area>();
		
		String selectQuery = "SELECT * FROM " + dbHelper.TABLE_AREA_DETAILS;
		
		Cursor cursor = null;
		cursor = dB.rawQuery(selectQuery, null);
		
		while(cursor.moveToNext()){
			
			Area area = new Area();
			
			area.setAreaId(cursor.getInt(cursor.getColumnIndex(dbHelper.AREA_ID)));
			area.setAreaName(cursor.getString(cursor.getColumnIndex(dbHelper.AREA_NAME)));
			area.setSpeedLimit(cursor.getDouble(cursor.getColumnIndex(dbHelper.AREA_SPEED_LIMIT)));
				
			results.add(area);
		}
		dB.close();
		return results;
	}
	
	
	public ArrayList<Area> getAllAreaById(int id) {
		if (dB == null) {
			open();
		} else if (!dB.isOpen()) {
			open();
		}
		
		ArrayList<Area> results = new ArrayList<Area>();
		
		String selectQuery = "SELECT * FROM " + dbHelper.TABLE_AREA_DETAILS+ " WHERE "+dbHelper.AREA_ID+"="+id;
		
		Cursor cursor = null;
		cursor = dB.rawQuery(selectQuery, null);
		
		while(cursor.moveToNext()){
			
			Area area = new Area();
			
			area.setAreaId(cursor.getInt(cursor.getColumnIndex(dbHelper.AREA_ID)));
			area.setAreaName(cursor.getString(cursor.getColumnIndex(dbHelper.AREA_NAME)));
			area.setSpeedLimit(cursor.getDouble(cursor.getColumnIndex(dbHelper.AREA_SPEED_LIMIT)));
				
			results.add(area);
		}
		dB.close();
		return results;
	}
	
}
